package com.lagou.server.handler;

import com.lagou.invoke.RpcRequest;
import com.lagou.invoke.RpcResponse;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Map;

/**
 * @author Kirito
 * @description:
 * @date 2020/05/26
 */
@Component
public class NettyInvocationHandler extends ChannelInboundHandlerAdapter implements ApplicationContextAware {

    private static ApplicationContext context;

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        // 请求处理开始时间
        long start = System.currentTimeMillis();
        RpcRequest request = (RpcRequest) msg;
        RpcResponse response = invoke(request);
        response.setStartTime(start);
        ctx.writeAndFlush(response);
    }

    private RpcResponse invoke(RpcRequest request) throws Exception {
        RpcResponse response = new RpcResponse();
        Map<String, ?> beans = context.getBeansOfType(Class.forName(request.getClassName()));
        Object bean = beans.get("userServiceImpl");

        if (null == bean) {
            response.setSuccess(false);
        }
        Method method = bean.getClass().getDeclaredMethod(request.getMethodName(), request.getParameterTypes());
        if (null != method) {
            method.setAccessible(true);
            response.setSuccess(true);
            response.setData(method.invoke(bean, request.getParameters()));
        } else {
            response.setSuccess(false);
        }
        return response;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }
}
